﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Red.Controls;
using Red.Controls.DataDriven;
using Red.Controls.Shell;
using Red.Controls.ViewModels;

namespace Red.Toolkit.WorldEditor
{
    /// <summary>
    /// Interaction logic for SceneTreeLayer.xaml
    /// </summary>
    [InteropControl( "WorldTreeLayer" )]
    public partial class SceneTreeLayer : UserControl
    {
        private static Canvas _layerIcon;
        private static Canvas _eyeIcon;
        private static Canvas _hiddenIcon;

        private bool _isVisible = true;

        static SceneTreeLayer()
        {
            _layerIcon = RedApplication.FindCanvasResource( "appbar_box_layered" );
            _eyeIcon = RedApplication.FindCanvasResource( "appbar_eye" );
            _hiddenIcon = RedApplication.FindCanvasResource( "appbar_eye_hide" );
        }

        public SceneTreeLayer()
        {
            InitializeComponent();
            DataContextChanged += OnDataContextChanged;
        }

        private void OnDataContextChanged( object sender, DependencyPropertyChangedEventArgs e )
        {
            InteropTreeItem treeItem = e.NewValue as InteropTreeItem;

            if ( treeItem == null )
                return;

            treeItem.Image = _layerIcon;
            treeItem.CanBeActivated = true;
            _visibilityButton.Icon = _eyeIcon;

            List<RedMenuDataItem> menu = new List<RedMenuDataItem>();
            menu = WorldEditorCommands.LayerItemCommands.Select( command => new RedMenuDataItem( new CommandWrapper( command, treeItem ) ) ).ToList();
            treeItem.SetMenu( menu );
        }

        private void SceneTreeLayer_ToggleVisibilityClick( object sender, RoutedEventArgs e )
        {
            var treeItem = DataContext as InteropTreeItem;
            HandleToggleVisibility( treeItem );
        }

        private void ToggleVisibility_Executed( object sender, ExecutedRoutedEventArgs e )
        {
            InteropTreeItem treeItem = e.Parameter as InteropTreeItem;
            HandleToggleVisibility( treeItem );
        }

        private void HandleToggleVisibility( InteropTreeItem treeItem )
        {
            if ( treeItem == null )
                return;

            _isVisible = !_isVisible;

            treeItem.Execute( "setVisibility", _isVisible );

            if ( _visibilityButton.Icon == _eyeIcon )
                _visibilityButton.Icon = _hiddenIcon;
            else
                _visibilityButton.Icon = _eyeIcon;
        }
    }
}
